package com.lantu.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lantu.common.utils.JwtUtil;
import com.lantu.common.vo.Result;
import com.lantu.sys.entity.*;
import com.lantu.sys.entity.Post;
import com.lantu.sys.service.IPostService;
import com.lantu.sys.service.IPostStudentService;
import com.lantu.sys.service.IStudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    private IPostService postService;

    @Autowired
    private IPostStudentService postStudentService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/all")
    public Result<List<Post>> getAllUser() {
        List<Post> list = postService.list();
        return Result.success(list, "查询成功");
    }

    @GetMapping("/getStudentByPostId/{id}")
    public Result<List<Student>> getStudentByPostId(@PathVariable("id") Integer postId) {
        List<PostStudent> list = postStudentService.list(new LambdaQueryWrapper<PostStudent>().eq(PostStudent::getPostId, postId));

        if (CollectionUtils.isEmpty(list)) {
            return Result.success(new ArrayList<>());
        }

        Set<Integer> studentIds = list.stream().map(i -> i.getStudentId()).collect(Collectors.toSet());
        List<Student> students = studentService.list(new LambdaQueryWrapper<Student>().in(Student::getId, studentIds));

        if (CollectionUtils.isEmpty(students)) {
            return Result.success(new ArrayList<>());
        }

        return Result.success(students, "查询成功");
    }

    @GetMapping("/list")
    public Result<Map<String, Object>> getPostList(@RequestParam(value = "name", required = false) String name,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize) {

        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(name), Post::getName, name);
        wrapper.orderByDesc(Post::getId);

        Page<Post> page = new Page<>(pageNo, pageSize);
        postService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);

    }

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addUser(@RequestBody PostDTO postDTO, @RequestHeader("X-Token") String token) {

        User loginUser = null;
        try {
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Post post = new Post();
        BeanUtils.copyProperties(postDTO, post);
        post.setTeacherId(loginUser.getId());
        post.setTeacher(loginUser.getUsername());

        postService.save(post);

        if (CollectionUtils.isEmpty(postDTO.getStudents())) {
            List<PostStudent> postStudents = postDTO.getStudents().stream().map(i -> {
                PostStudent postStudent = new PostStudent();
                postStudent.setStudentId(i);
                postStudent.setPostId(post.getId());
                return postStudent;
            }).collect(Collectors.toList());

            postStudentService.saveBatch(postStudents);
        }
        return Result.success("新增用户成功");
    }

    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public Result<?> updateUser(@RequestBody PostDTO postDTO, @RequestHeader("X-Token") String token) {

        User loginUser = null;
        try {
            loginUser = jwtUtil.parseToken(token, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Post post = new Post();
        BeanUtils.copyProperties(postDTO, post);

        postService.updateById(post);


        postStudentService.remove(new LambdaQueryWrapper<PostStudent>().eq(PostStudent::getPostId, post.getId()));

        if (!CollectionUtils.isEmpty(postDTO.getStudents())) {
            List<PostStudent> postStudents = postDTO.getStudents().stream().map(i -> {
                PostStudent postStudent = new PostStudent();
                postStudent.setStudentId(i);
                postStudent.setPostId(post.getId());
                return postStudent;
            }).collect(Collectors.toList());

            postStudentService.saveBatch(postStudents);
        }

        return Result.success("修改用户成功");
    }

    @GetMapping("/{id}")
    public Result<PostVO> getPostById(@PathVariable("id") Integer id) {
        Post post = postService.getById(id);
        List<PostStudent> list = postStudentService.list(new LambdaQueryWrapper<PostStudent>().eq(PostStudent::getPostId, id));
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        postVO.setStudents(list.stream().map(i -> i.getStudentId()).collect(Collectors.toList()));

        return Result.success(postVO);
    }

    @DeleteMapping("/{id}")
    public Result<Post> deleteUserById(@PathVariable("id") Integer id) {
        postService.removeById(id);
        postStudentService.remove(new LambdaQueryWrapper<PostStudent>().eq(PostStudent::getPostId, id));
        return Result.success("删除用户成功");
    }
}
